/*
 * @Author: lokei
 * @Date: 2022-10-23 18:07:51
 * @LastEditors: lokei
 * @LastEditTime: 2022-12-28 22:07:56
 * @Description: 
 */
package cn.lokei.task.entity.iot.mqtt;

import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class MqttReceriveCallback implements MqttCallback {
	private MyMqttClient myMqttClient;

	public MqttReceriveCallback(MyMqttClient myMqttClient) {
		this.myMqttClient = myMqttClient;
	}

	@Override
	public void connectionLost(Throwable cause) {
		log.error("连接断开，下面做重连...");
		long reconnectTimes = 1;
		while (true) {
			try {
				if (myMqttClient.mqttClient.isConnected()) {

					log.warn("mqtt reconnect success end");

					return;

				}
				log.warn("mqtt reconnect times = {} try again...", reconnectTimes++);
				myMqttClient.mqttClient.reconnect();
			} catch (MqttException e) {
				log.error("", e);
			}

			try {
				Thread.sleep(1000);
			} catch (InterruptedException e1) {
				// e1.printStackTrace();
			}
		}
	}

	@Override
	public void messageArrived(String topic, MqttMessage message) throws Exception {
		System.out.println("Client 接收消息主题 : " + topic);
		System.out.println("Client 接收消息Qos : " + message.getQos());
		System.out.println("Client 接收消息内容 : " + new String(message.getPayload()));

	}

	@Override
	public void deliveryComplete(IMqttDeliveryToken token) {

	}

}
